#include <stdio.h>
#include <pthread.h>
#include <condition_variable>

//#include <iostream>
//using std::cout;
//using std::endl;

#define LOG() \
    printf("文件：%s | 行号：%d | 函数：%s \n", __FILE__, __LINE__, __FUNCTION__);

pthread_mutex_t mutex;
pthread_cond_t cond;
//enum flag {"A", "B", "C"};    // 枚举成员的标识符是不能用字符串字面量（“A”)
enum Flag {A, B, C};
Flag flag = A;

void* t1(void *)
{
    LOG();
    pthread_mutex_lock(&mutex);
    while(flag != A)
    {
        pthread_cond_wait(&cond, &mutex);
    }
    printf("A\n");
    flag = B;
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);

    pthread_mutex_lock(&mutex);
    while(flag != C)
    {
        pthread_cond_wait(&cond, &mutex);
    }
    printf("C\n");
    flag = A;
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);

    return nullptr;
}

void* t2(void *)
{
    LOG();
    pthread_mutex_lock(&mutex);

    //if(flag == B)
    //{
    //    pthread_cond_wait(&cond, &mutex);
    //}
    
    while(flag != B)
    {
        pthread_cond_wait(&cond, &mutex);   // 加锁保证原子操作与避免忙等待
    }
    

    printf("B\n");
    flag = C;
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);

    return nullptr;
}

void test(){
    LOG();
    pthread_t pthid1, pthid2;

    pthread_create(&pthid1, NULL, t1, NULL);
    pthread_create(&pthid2, NULL, t2, NULL);

    pthread_join(pthid1, NULL);
    pthread_join(pthid2, NULL);
    LOG();
}

int main()
{
    test();
    return 0;
}

